package com.lianzhihui.romeex.ui.me;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.zxing.client.android.Intents;
import com.lianzhihui.romeex.R;
import com.lianzhihui.romeex.bean.SaveAddressInfo;
import com.lianzhihui.romeex.bean.WalletMainBean;
import com.lianzhihui.romeex.config.AppConstants;
import com.lianzhihui.romeex.inter.SelectListener;
import com.lianzhihui.romeex.ui.base.BaseActivity;
import com.lianzhihui.romeex.ui.me.dialog.DeleteAddressDialog;
import com.lianzhihui.romeex.ui.qrcode.ScanActivity;
import com.lianzhihui.romeex.utils.GsonUtil;
import com.lianzhihui.romeex.utils.LogUtil;
import com.lianzhihui.romeex.utils.NoDoubleClickUtils;
import com.lianzhihui.romeex.utils.QrUtils.QRUtils;
import com.lianzhihui.romeex.utils.StatusBarUtil;
import com.lianzhihui.romeex.utils.UserUtils;
import com.lianzhihui.romeex.widget.dialog.CoinSelDialog;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

import static com.lianzhihui.romeex.utils.StringTool.addHead;

/**
 * @ProjectName: romeex
 * @Package: com.lianzhihui.romeex.ui.me
 * @ClassName: AddAddressActivity
 * @Description: java类作用描述
 * @Author: zhanghong
 * @CreateDate: 2020/11/2 15:47
 * @UpdateUser: 更新者：
 * @UpdateDate: 2020/11/2 15:47
 * @UpdateRemark: 更新说明：
 * @Version: 1.0
 */
public class EditAddressActivity extends BaseActivity {


    @BindView(R.id.include_top_iv_back)
    ImageView includeTopIvBack;
    @BindView(R.id.include_top_lin_newback)
    LinearLayout includeTopLinNewback;
    @BindView(R.id.include_top_tv_title)
    TextView includeTopTvTitle;
    @BindView(R.id.include_top_iv_right_second)
    ImageView includeTopIvRightSecond;
    @BindView(R.id.include_top_tv_right)
    TextView includeTopTvRight;
    @BindView(R.id.include_top_lin_right)
    LinearLayout includeTopLinRight;
    @BindView(R.id.include_top_lin_background)
    LinearLayout includeTopLinBackground;
    @BindView(R.id.app_top_bar)
    LinearLayout appTopBar;
    @BindView(R.id.hint_title)
    TextView hintTitle;
    @BindView(R.id.tv_currency)
    TextView tvCurrency;
    @BindView(R.id.tv_change_coins)
    RelativeLayout tvChangeCoins;
    @BindView(R.id.et_address)
    EditText etAddress;
    @BindView(R.id.iv_scan)
    ImageView ivScan;
    @BindView(R.id.et_note)
    EditText etNote;
    @BindView(R.id.tv_submit)
    TextView tvSubmit;
    private int clickIndex;
    private SaveAddressInfo addressInfo;
    private SaveAddressInfo.Address currentAddress;
    private String currency;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_edit_address;
    }

    @Override
    protected void initView() {
        StatusBarUtil.setTransparent(this);
        StatusBarUtil.setStatusBarTextColor(this, false);
        includeTopTvTitle.setText(getResources().getString(R.string.text_edit_address));
        includeTopIvRightSecond.setVisibility(View.VISIBLE);
        includeTopIvRightSecond.setBackground(getResources().getDrawable(R.drawable.me_icon_delete));

    }

    @Override
    protected void initData() {
        Bundle extras = getIntent().getExtras();
        if (extras != null) {
            clickIndex = Integer.parseInt(extras.getString(AppConstants.ITEM_INDEX, "-1"));
            addressInfo = (SaveAddressInfo) extras.get(AppConstants.ITEM_OBJ);
        }
        currentAddress = addressInfo.getList().get(clickIndex);
        etAddress.setText(currentAddress.getAddress());
        etNote.setText(currentAddress.getNote());
        tvCurrency.setText(currentAddress.getUserCurrencyName());
//        String currentSaveAddressList = UserUtils.getCurrentSaveAddressList();
//        if (!currentSaveAddressList.isEmpty()) {
//            saveAddressInfo = GsonUtil.GsonToBean(currentSaveAddressList, SaveAddressInfo.class);
//        }

    }


    @OnClick({R.id.include_top_iv_back, R.id.tv_change_coins, R.id.include_top_iv_right_second, R.id.tv_submit, R.id.iv_scan})
    public void OnClick(View v) {
        if (NoDoubleClickUtils.isDoubleClick()) {
            switch (v.getId()) {
                case R.id.include_top_iv_back:
                    finish();
                    break;
                case R.id.iv_scan:
                    //扫描
                    Intent intent = new Intent(this, ScanActivity.class);
                    startActivityForResult(intent, AppConstants.ME_REQUEST_CODE_SCAN);
                    break;
                case R.id.tv_submit:
                    //提交
                    if (check()) {
                        showLoading("");
                        Observable.create(new ObservableOnSubscribe<Object>() {
                            @Override
                            public void subscribe(ObservableEmitter<Object> emitter) throws Exception {
                                if (addressInfo != null) {
                                    currentAddress.setAddress(etAddress.getText().toString().trim());
                                    currentAddress.setNote(etNote.getText().toString().trim());
                                    currentAddress.setUserCurrencyName(tvCurrency.getText().toString().trim());
                                }
                                UserUtils.setCurrentSaveAddressList(GsonUtil.GsonString(addressInfo));
                                emitter.onComplete();
                            }
                        }).subscribeOn(Schedulers.io())
                                .subscribe(new Observer<Object>() {
                                    @Override
                                    public void onSubscribe(Disposable d) {

                                    }

                                    @Override
                                    public void onNext(Object o) {

                                    }

                                    @Override
                                    public void onError(Throwable e) {

                                    }

                                    @Override
                                    public void onComplete() {
                                        Intent intentResult = new Intent();
                                        Bundle bundle = new Bundle();
                                        bundle.putSerializable(AppConstants.ITEM_OBJ, addressInfo);
                                        intentResult.putExtras(bundle);
                                        setResult(RESULT_OK, intentResult);
                                        dismissLoading();
                                        finish();
                                    }
                                });
                    }
                    break;
                case R.id.include_top_iv_right_second:
                    //删除地址
                    DeleteAddressDialog deleteAddressDialog = new DeleteAddressDialog(this);
                    deleteAddressDialog.setCancelable(false);
                    deleteAddressDialog.bottom();
                    deleteAddressDialog.fullWidth();
                    deleteAddressDialog.setCallback(new DeleteAddressDialog.Callback() {
                        @Override
                        public void confirm() {
                            if (addressInfo != null) {
                                addressInfo.getList().remove(clickIndex);
                                Intent intent = new Intent();
                                Bundle bundle = new Bundle();
                                bundle.putSerializable(AppConstants.ITEM_OBJ, addressInfo);
                                intent.putExtras(bundle);
                                setResult(RESULT_OK, intent);
                            }
                            finish();
                        }
                    });
                    deleteAddressDialog.show();

                    break;
                case R.id.tv_change_coins:
                    //修改货币
                    CoinSelDialog selector = new CoinSelDialog(mActivity);
                    selector.setListener(new SelectListener() {
                        @Override
                        public void onSelect(int position) {
                            WalletMainBean.CoinBean coin = selector.adapter.getItem(position);
                            currency = coin.getCoinNameAlias();
                            tvCurrency.setText(currency);
                        }
                    });
                    selector.show();
                    break;
                default:
                    break;
            }
        }
    }

    private boolean check() {
        if (etAddress.getText().toString().trim().isEmpty()) {
            toast(getResources().getString(R.string.text_input_take_out_address));
            return false;
        }
        return true;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        // 扫描二维码/条码回传
        //todo 二维码 导入私钥回调
        if (requestCode == AppConstants.ME_REQUEST_CODE_SCAN && resultCode == RESULT_OK) {
            if (data != null) {
                //返回的文本内容
                String content = data.getStringExtra(Intents.Scan.RESULT);
                LogUtil.error("ramon", "result: " + content);
                if (TextUtils.isEmpty(content)) {
                    toast("无效二维码");
                    return;
                }
                if (QRUtils.scanType(content) == 2) {
                    //解析私钥，填入私钥
                    etAddress.setText(addHead(QRUtils.getContentString(content, 2)));
                }

            }
        }
    }
}
